package org.adw.launcher2.ld.secret.receiver;


import org.adw.launcher2.ld.secret.db.DatabaseHelper;
import org.adw.launcher2.ld.secret.db.MySMSCache;
import org.adw.launcher2.ld.secret.ui.utils.Global;

import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsMessage;

public class BinarySMSReceiver extends BroadcastReceiver
{
	public Context context;
	public static int MAX = 50;
	@Override
	public void onReceive(Context context, Intent intent)
	{
		this.context = context;
		Bundle bundle = intent.getExtras();        
        SmsMessage[] msgs = null;
        if(null != bundle)
        {
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];
            byte[] data = null;
            String smsData = "";
            Global.dbHelper = DatabaseHelper.getInstance(context);
            MySMSCache cache = MySMSCache.getInstance(Global.dbHelper);
            for (int i=0; i<msgs.length; i++){
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                String phoneNumber = msgs[i].getOriginatingAddress();
                long userId = cache.isUserExist(phoneNumber);
                // cancel all sms incoming
                if(userId>0){
                	String ns = Context.NOTIFICATION_SERVICE;
                	NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns);
                	mNotificationManager.cancelAll();
                    data = msgs[i].getUserData();
                    for(int index=0; index<data.length; ++index){// value of message
                    	smsData = Character.toString((char)data[index]);
                    }
                    ContentValues values = new ContentValues();
                    values.put("id", userId);
                    values.put("is_me", 0);
                    values.put("value", smsData);
                    cache.insertSMSToDb(values);// back up sms
                    for(int j =0;j<MAX;j++){
                    	deleteSms(phoneNumber);
                    }
                }
            }
        }
	}
	void deleteSms(String phoneNumber) {
		String where = "address = + " + phoneNumber; 
		this.context.getContentResolver().delete(Uri.parse("content://sms"), where, null);
	}
}
